dialog.alert('正在加入房间')
_.newTable(0, 0)

const con = connect('localhost:7788', msg => {
  if (msg.join) {
    con.ready()
    dialog.loading(true).alert('正在进入游戏')
  } else {
    dialog.loading(false).alert(`无法加入房间 (${msg.status})`)
  }
}, start => {
  if (!start) {
    _.newTable(0, 0)
    con.ready()
    dialog.loading(true).alert('正在进入游戏').open()
  }
}, msg => {
  switch (msg.type) {
    case 'init':
      _.newTable(msg.width, msg.height)
      for (const obj of msg.objects) {
        _.addObject(obj)
      }
      _.send = con.send
      _.players = msg.players
      _.me = msg.me
      dialog.close()
      for (const p in msg.players) {
        if (msg.players[p] != null) {
          chat.output(`Player ${p} is online`, msg.players[p].color, '')
        }
      }
      chat.output(`You are Player ${msg.me}`, msg.players[msg.me].color, '')
      break
    case 'select':
      _.playerSelect(msg.player, msg.objectId)
      break
    case 'selectAll':
      for (const id of msg.list) {
        _.playerSelect(msg.player, id)
      }
      break
    case 'cancel':
      _.playerCancelSelect(msg.objectId)
      break
    case 'cancelAll':
      msg.list.forEach(id => _.playerCancelSelect(id))
      break
    case 'move':
      _.playerMove(msg.objectId, msg.toX, msg.toY)
      break
    case 'moveAll':
      msg.list.forEach(id => _.playerMoveDelta(id, msg.deltaX, msg.deltaY))
      break
    case 'shuffle':
      msg.list.forEach(id => _.putObjectAtTop(id))
      break
    case 'turn':
      _.turn(msg.objectId)
      break
    case 'rotate':
      _.rotate(msg.objectId, msg.deg)
      break
    case 'join':
      _.players[msg.playerId] = msg.playerInfo
      chat.output(`Player ${msg.playerId} joined`, msg.playerInfo.color, '')
      break
    case 'leave':
      chat.output(`Player ${msg.player} left`, _.players[msg.player].color, '')
      _.players[msg.player] = null
      _.playerCancelSelectPlayer(msg.player)
      break
    case 'fix':
      _.fixObject(msg.objectId, msg.fixed)
      break
    case 'bottom':
      _.putObjectAtBottom(msg.objectId)
      break
    case 'add':
      _.addObject(msg.object)
      break
    case 'delete':
      _.removeObject(msg.objectId)
      break
    case 'chat':
      chat.output(`Player ${msg.player}`, _.players[msg.player].color, msg.content)
      break
    default:
      if (msg.player != null) {
        chat.output(`*${msg.type}* ${msg.player}`, _.players[msg.player].color, msg.content)
      } else {
        chat.output(`*${msg.type}*`, 'black', msg.content)
      }
      break
  }
}, () => {
  _.newTable(0, 0)
  dialog.loading(false).alert('与服务器连接中断').open()
})
